﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using Maticsoft.Common;
using System.Drawing;
using LTP.Accounts.Bus;
namespace XDSoft.Web.TB_Brand
{
    public partial class List : Page
    {
        XDSoft.BLL.TB_Brand bll = new XDSoft.BLL.TB_Brand();

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                bindDDL();
                gridView.BorderColor = ColorTranslator.FromHtml(Application[Session["Style"].ToString() + "xtable_bordercolorlight"].ToString());
                gridView.HeaderStyle.BackColor = ColorTranslator.FromHtml(Application[Session["Style"].ToString() + "xtable_titlebgcolor"].ToString());
                btnDelete.Attributes.Add("onclick", "return confirm(\"你确认要删除吗？\")");
                BindData();
            }
        }

        private void bindDDL()
        {
            XDSoft.BLL.TB_Options oBll = new XDSoft.BLL.TB_Options();
            this.ddlTypeCode.AppendDataBoundItems = true;
            this.ddlTypeCode.Items.Add(new ListItem("", ""));
            this.ddlTypeCode.DataSource = oBll.GetModelList("parent='" + EnumCommon.OptionsType.InternationalCode.ToString() + "'");
            this.ddlTypeCode.DataTextField = "name";
            this.ddlTypeCode.DataValueField = "id";
            this.ddlTypeCode.DataBind();
            this.ddlStatus.AppendDataBoundItems = true;
            this.ddlStatus.Items.Add(new ListItem("", ""));
            this.ddlStatus.DataSource = oBll.GetModelList("parent='" + EnumCommon.OptionsType.BrandStatus.ToString() + "'");
            this.ddlStatus.DataTextField = "name";
            this.ddlStatus.DataValueField = "id";
            this.ddlStatus.DataBind();
            this.ddlBrandType.AppendDataBoundItems = true;
            this.ddlBrandType.Items.Add(new ListItem("", ""));
            this.ddlBrandType.DataSource = oBll.GetModelList("parent='" + EnumCommon.OptionsType.BrandType.ToString() + "'");
            this.ddlBrandType.DataTextField = "name";
            this.ddlBrandType.DataValueField = "id";
            this.ddlBrandType.DataBind();

            this.ddlExpire.AppendDataBoundItems = true;
            this.ddlExpire.Items.Add(new ListItem("", ""));
            for (int i = 6; i > 0; i--)
            {
                int day = 30 * i;
                ListItem li = new ListItem(i.ToString() + "个月内", day.ToString());
                this.ddlExpire.Items.Add(li);
                if (!string.IsNullOrEmpty(Request.Params["ExpireMonth"]))
                {
                    if (Request.Params["ExpireMonth"] == day.ToString())
                        this.ddlExpire.SelectedValue = Request.Params["ExpireMonth"];
                }
            }
            this.ddlExpire.DataBind();

            this.ddlServiceExpire.AppendDataBoundItems = true;
            this.ddlServiceExpire.Items.Add(new ListItem("", ""));
            for (int i = 1; i > 0; i--)
            {
                int day = 30 * i;
                ListItem li = new ListItem(i.ToString() + "个月内", day.ToString());
                this.ddlServiceExpire.Items.Add(li);
                if (!string.IsNullOrEmpty(Request.Params["ServiceExpire"]))
                {
                    if (Request.Params["ServiceExpire"] == day.ToString())
                        this.ddlServiceExpire.SelectedValue = Request.Params["ServiceExpire"];
                }
            }
            this.ddlServiceExpire.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string idlist = GetSelIDlist();
            if (idlist.Trim().Length == 0)
                return;
            bll.DeleteList(idlist);
            BindData();
        }

        #region gridView
        private string getWhere()
        {
            StringBuilder strWhere = new StringBuilder();
            if (!string.IsNullOrEmpty(this.txtApplyManName.Text))
            {
                if (strWhere.Length > 0)
                    strWhere.AppendLine(" and ");
                strWhere.AppendFormat("applyManName like '%{0}%'", this.txtApplyManName.Text);
            }

            if (!string.IsNullOrEmpty(this.txtClientService.Text))
            {
                if (strWhere.Length > 0)
                    strWhere.AppendLine(" and ");
                strWhere.AppendFormat("clientService like '%{0}%'", this.txtClientService.Text);
            }

            if (!string.IsNullOrEmpty(this.txtProductList.Text))
            {
                if (strWhere.Length > 0)
                    strWhere.AppendLine(" and ");
                strWhere.AppendFormat("productList like '%{0}%'", this.txtProductList.Text);
            }


            if (!string.IsNullOrEmpty(this.txtRegCode.Text))
            {
                if (strWhere.Length > 0)
                    strWhere.AppendLine(" and ");
                strWhere.AppendFormat("regCode like '%{0}%'", this.txtRegCode.Text);
            }

            if (!string.IsNullOrEmpty(this.ddlBrandType.SelectedValue))
            {
                if (strWhere.Length > 0)
                    strWhere.AppendLine(" and ");
                strWhere.AppendFormat("brandType ='{0}'", this.ddlBrandType.SelectedValue);
            }

            if (!string.IsNullOrEmpty(this.ddlStatus.SelectedValue))
            {
                if (strWhere.Length > 0)
                    strWhere.AppendLine(" and ");
                strWhere.AppendFormat("status ='{0}'", this.ddlStatus.SelectedValue);
            }

            if (!string.IsNullOrEmpty(this.ddlTypeCode.SelectedValue))
            {
                if (strWhere.Length > 0)
                    strWhere.AppendLine(" and ");
                strWhere.AppendFormat("typeCode ='{0}'", this.ddlTypeCode.SelectedValue);
            }

            if (!string.IsNullOrEmpty(this.txtApplyDateS.Text) && !string.IsNullOrEmpty(this.txtApplyDateE.Text))
            {
                if (strWhere.Length > 0)
                    strWhere.AppendLine(" and ");
                strWhere.AppendFormat("(applyDate >'{0}' and applyDate<'{1}')", this.txtApplyDateS.Text, Convert.ToDateTime(this.txtApplyDateE.Text).AddDays(1).AddSeconds(-1).ToString("yyyy-MM-dd hh:mm:ss"));
            }

            if (!string.IsNullOrEmpty(this.ddlExpire.SelectedValue))
            {
                if (strWhere.Length > 0)
                    strWhere.AppendLine(" and ");
                strWhere.AppendFormat("(ABS(DATEDIFF(day,GETDATE(),specialEndDate))<={0})", this.ddlExpire.SelectedValue);
            }

            if (!string.IsNullOrEmpty(this.ddlServiceExpire.SelectedValue))
            {
                if (strWhere.Length > 0)
                    strWhere.AppendLine(" and ");
                strWhere.AppendFormat("(ABS(DATEDIFF(day,GETDATE(),serviceExpire))<={0})", this.ddlServiceExpire.SelectedValue);
            }

            return strWhere.ToString();
        }

        public void BindData()
        {
            #region
            //if (!Context.User.Identity.IsAuthenticated)
            //{
            //    return;
            //}
            //AccountsPrincipal user = new AccountsPrincipal(Context.User.Identity.Name);
            //if (user.HasPermissionID(PermId_Modify))
            //{
            //    gridView.Columns[6].Visible = true;
            //}
            //if (user.HasPermissionID(PermId_Delete))
            //{
            //    gridView.Columns[7].Visible = true;
            //}
            #endregion

            string strWhere = getWhere();
            DataSet ds = bll.GetList(strWhere.ToString());
            if (ds != null && ds.Tables.Count > 0)
            {
                XDSoft.BLL.TB_Options oBll = new XDSoft.BLL.TB_Options();
                XDSoft.BLL.TB_Clients cBll = new XDSoft.BLL.TB_Clients();
                string vPath = WebCommon.GetVPath(this.Page);
                ds.Tables[0].Columns.Add("clientName");
                ds.AcceptChanges();
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {

                    if (ds.Tables[0].Rows[i]["icon"] != null && !string.IsNullOrEmpty(ds.Tables[0].Rows[i]["icon"].ToString()))
                        ds.Tables[0].Rows[i]["icon"] = vPath + ds.Tables[0].Rows[i]["icon"].ToString().Replace(@"\", @"/").Replace("Big", "Small");

                    if (ds.Tables[0].Rows[i]["typeCode"] != null && !string.IsNullOrEmpty(ds.Tables[0].Rows[i]["typeCode"].ToString()))
                        ds.Tables[0].Rows[i]["typeCode"] = oBll.GetModel(Convert.ToInt32(ds.Tables[0].Rows[i]["typeCode"])).name;
                    if (ds.Tables[0].Rows[i]["brandType"] != null && !string.IsNullOrEmpty(ds.Tables[0].Rows[i]["brandType"].ToString()))
                        ds.Tables[0].Rows[i]["brandType"] = oBll.GetModel(Convert.ToInt32(ds.Tables[0].Rows[i]["brandType"])).name;
                    if (ds.Tables[0].Rows[i]["status"] != null && !string.IsNullOrEmpty(ds.Tables[0].Rows[i]["status"].ToString()))
                        ds.Tables[0].Rows[i]["status"] = oBll.GetModel(Convert.ToInt32(ds.Tables[0].Rows[i]["status"])).name;

                    if (ds.Tables[0].Rows[i]["client"] != null && ds.Tables[0].Rows[i]["client"] != DBNull.Value)
                        ds.Tables[0].Rows[i]["clientName"] = cBll.GetModel(Convert.ToInt32(ds.Tables[0].Rows[i]["client"])).clientName;
                }
            }
            gridView.DataSource = ds;
            ViewState["QueryDataSet"] = ds;
            gridView.DataBind();
        }

        protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridView.PageIndex = e.NewPageIndex;
            BindData();
        }
        protected void gridView_OnRowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                //e.Row.Cells[0].Text = "<input id='Checkbox2' type='checkbox' onclick='CheckAll()'/><label></label>";
            }
        }
        protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string color = Color.White.ToKnownColor().ToString();
            
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DateTime dt = new DateTime();
                if (DateTime.TryParse(((DataRowView)e.Row.DataItem).Row.ItemArray[10].ToString(),out dt))
                {
                    TimeSpan ts1 = new TimeSpan(dt.Ticks);
                    TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
                    TimeSpan ts = ts1.Subtract(ts2).Duration();
                    if (ts.Days<30)
                        color = Color.Red.ToKnownColor().ToString();
                    else if ((ts.Days<90))
                        color = Color.Orange.ToKnownColor().ToString();
                    else if ((ts.Days<180))
                        color = Color.Yellow.ToKnownColor().ToString();
                }

                LinkButton linkbtnDel = (LinkButton)e.Row.FindControl("LinkButton1");
                linkbtnDel.Attributes.Add("onclick", "return confirm(\"你确认要删除吗\")");

                //object obj1 = DataBinder.Eval(e.Row.DataItem, "Levels");
                //if ((obj1 != null) && ((obj1.ToString() != "")))
                //{
                //    e.Row.Cells[1].Text = obj1.ToString();
                //}

            }
                e.Row.Attributes.Add("style", "background:" + color);
        }

        protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //#warning 代码生成警告：请检查确认真实主键的名称和类型是否正确
            //int ID = (int)gridView.DataKeys[e.RowIndex].Value;
            //bll.Delete(ID);
            //gridView.OnBind();
        }

        private string GetSelIDlist()
        {
            string idlist = "";
            bool BxsChkd = false;
            for (int i = 0; i < gridView.Rows.Count; i++)
            {
                CheckBox ChkBxItem = (CheckBox)gridView.Rows[i].FindControl("DeleteThis");
                if (ChkBxItem != null && ChkBxItem.Checked)
                {
                    BxsChkd = true;
                    //#warning 代码生成警告：请检查确认Cells的列索引是否正确
                    if (gridView.DataKeys[i].Value != null)
                    {
                        idlist += gridView.DataKeys[i].Value.ToString() + ",";
                    }
                }
            }
            if (BxsChkd)
            {
                idlist = idlist.Substring(0, idlist.LastIndexOf(","));
            }
            return idlist;
        }

        #endregion

        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (ViewState["QueryDataSet"] != null)
            {
                DataSet ds = (DataSet)ViewState["QueryDataSet"];
                if (ds != null && ds.Tables.Count > 0)
                {
                    DataSet newDs = new DataSet();
                    string tableName = "sheet1";
                    DataTable dt = WebCommon.ChangeDataTableFieldAttrName(typeof(Model.TB_Brand), ds.Tables[0], tableName);
                    newDs.Tables.Add(dt);
                    ExcelHelper.ToExcel(newDs, tableName + ".xls", this.Page.Response);
                }
            }
        }


    }
}
